package com.pactera.rabbit;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.pactera.common.utils.StrUtils;
import com.rabbitmq.client.Channel;

@Component
@EnableTransactionManagement(proxyTargetClass = true)
public class RabbitMqFonoutListener implements ChannelAwareMessageListener{

	/** 0-不同步；1-同步；2-不处理 */
    public static final String FD_SYNC_SYS = "1";
    public static final String FD_SYNC_SYS_HANDLE_NO = "2";
    /** 1--有效；2--无效 */
    public static final Integer FD_AVAILABLE = 1;
    public static final Integer NOT_AVAILABLE = 2;
    /** -1--未删除；0--删除 */
    public static final Integer NOT_DELETE = -1;
    public static final Integer ISDELETE = 0;
	
	@Override
	public void onMessage(Message message, Channel channel) throws Exception {
    	try { 
			 byte[] body = message.getBody();
			 String receiveMsg = new String(body,"UTF-8");
			 System.out.println("receive message : ===" + receiveMsg);
			 if(StrUtils.isNotEmpty(receiveMsg)) {
				 JSONObject jsonObject = JSONObject.parseObject(receiveMsg);
				 String opType = jsonObject.getString("opType");
				 String dataType = jsonObject.getString("dataType");
				 if(dataType.equals("uc_org")) {
					 if(opType.equals("D")) {
						 String dataSid = jsonObject.getString("dataSid");
						 //删除组织机构
						 deleteDepart(dataSid);
					 }else {
						 JSONObject data =  (JSONObject) jsonObject.get("result");
						 String fdSyncSys = data.getString("fd_sync_sys");
						 if(StrUtils.isNotEmpty(fdSyncSys)) {
							 String fdAvailable = data.getString("fd_available");
							 String fdIsdelete = data.getString("fd_isdelete");
							 String flag = fdSyncSys.charAt(2)+"";
							 if(fdSyncSys.length()>2) {
								 flag =fdSyncSys.charAt(2)+"";
							 }
							 if(flag.equals(FD_SYNC_SYS)) {
								 if(fdAvailable.equals(FD_AVAILABLE) && fdIsdelete.equals(NOT_DELETE)) {
									 saveDepart(jsonObject);
								 }
							 }
						 }
					 }
				 }
			 }
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
     }
	
	@Transactional
	public void saveDepart(JSONObject jsonObject) {
		JSONObject jsonResult =  (JSONObject) jsonObject.get("result");
		String fdSid = jsonResult.getString("fd_sid");
	}
	
	@Transactional
	public void deleteDepart(String dataSid) {
		
	}

}
